package com.kaikeba.wx.controller;

import com.kaikeba.bean.BootStrapTableExpress;
import com.kaikeba.bean.Express;
import com.kaikeba.bean.Message;
import com.kaikeba.bean.User;
import com.kaikeba.exception.DuplicateCodeException;
import com.kaikeba.mvc.ResponseBody;
import com.kaikeba.service.ExpressService;
import com.kaikeba.util.DateFormatUtil;
import com.kaikeba.util.JSONUtil;
import com.kaikeba.util.UserUtil;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Stream;

public class ExpressController {

    @ResponseBody("/wx/findExpressByUserPhone.do")
    public String findExpressByUserPhone(HttpServletRequest request, HttpServletResponse response){
        User wxUser = UserUtil.getWxUser(request.getSession());
        String phoneNumber = wxUser.getPhoneNumber();
        List<Express> list = ExpressService.findByUserPhone(phoneNumber);
        List<BootStrapTableExpress> list2 = new ArrayList<>();
        for(Express e : list){
            String inTime = DateFormatUtil.format(e.getInTime());
            String outTime = e.getOutTime()==null?"未取件":DateFormatUtil.format(e.getOutTime());
            String status = e.getStatus()==1?"已取件":"未取件";
            String code = e.getCode()==null?"已取件":e.getCode();
            BootStrapTableExpress e2 = new BootStrapTableExpress(e.getId(),e.getNumber(),e.getUserName(),e.getUserPhone(),e.getCompany(),code,inTime,outTime,status,e.getSysPhone());
//            System.out.println(e2.toString());
            list2.add(e2);
        }
        Message msg = new Message();
        if(list2.size()==0){
            msg.setStatus(-1);
        }else{
            msg.setStatus(0);
            /** 下面使用的是新技术 流（Stream）的使用，
             * 可以非常方便的将数据分成两部分，但是不会操作原来的数据，是新的数据
             * 还提供了对流数据进行排序的方法
             * 最后可以使用流的toArray()转化成数组
             **/
            Stream<BootStrapTableExpress> status0Express = list2.stream().filter(express -> {
                if (express.getStatus().equals("未取件")) {//未取件
                    return true;
                } else {
                    return false;
                }
            }).sorted((o1,o2) ->{
                return (int) ((int) DateFormatUtil.toTime(o1.getInTime())-DateFormatUtil.toTime(o2.getInTime()));
            });
            Stream<BootStrapTableExpress> status1Express = list2.stream().filter(express -> {
                if (express.getStatus().equals("已取件")) {//已取件
                    return true;
                } else {
                    return false;
                }
            }).sorted(((o1, o2) -> {
                return (int) ((int) DateFormatUtil.toTime(o1.getOutTime())-DateFormatUtil.toTime(o2.getOutTime()));
            }));

            Object[] s0 = status0Express.toArray();
            Object[] s1 = status1Express.toArray();
            Map data = new HashMap<>();
            data.put("status0",s0);
            data.put("status1",s1);
            msg.setData(data);
        }
        String json = JSONUtil.toJSON(msg);
        return json;
    }

    @ResponseBody("/wx/findExpressByNumber.do")
    public String findExpressByNumber(HttpServletRequest request, HttpServletResponse response){
        String expressNum = request.getParameter("expressNum");
        Message msg = new Message();
        if(ExpressService.findByNumber(expressNum)!=null){
            Express e = ExpressService.findByNumber(expressNum);
            String code = e.getCode();
            if(code!=null) {
                msg.setResult("取件码为" + code);
            }else{
                msg.setResult("该快递已被取走");
            }
        }else{
            msg.setResult("没有该快递");
        }


        String json = JSONUtil.toJSON(msg);
        return json;
    }

    @ResponseBody("/wx/userExpressList.do")
    public String expressList(HttpServletRequest request, HttpServletResponse response){
        String userPhone = request.getParameter("userPhone");
        List<Express> list = ExpressService.findByUserPhoneAndStatus(userPhone,0);
        List<BootStrapTableExpress> list2 = new ArrayList<>();
        for(Express e : list){
            String inTime = DateFormatUtil.format(e.getInTime());
            String outTime = e.getOutTime()==null?"未取件":DateFormatUtil.format(e.getOutTime());
            String status = e.getStatus()==1?"已取件":"未取件";
            String code = e.getCode()==null?"已取件":e.getCode();
            BootStrapTableExpress e2 = new BootStrapTableExpress(e.getId(),e.getNumber(),e.getUserName(),e.getUserPhone(),e.getCompany(),code,inTime,outTime,status,e.getSysPhone());
//            System.out.println(e2.toString());
            list2.add(e2);
        }
        Message msg = new Message();
        if(list.size()==0){
            //没有快递或者查找失败
            msg.setStatus(-1);
            msg.setResult("未查询到快递");
        }else{
            msg.setStatus(0);
            msg.setResult("查询到存在快递");
            msg.setData(list2);
        }
        String json = JSONUtil.toJSON(msg);
        return json;
    }

    @ResponseBody("/wx/addExpress.do")
    public String addExpress(HttpServletRequest request, HttpServletResponse response){
        String expressId = request.getParameter("expressId");
        String username = request.getParameter("username");
        String phone = request.getParameter("phone");
        String company = request.getParameter("company");
        Express e = new Express();
        e.setNumber(expressId);
        e.setUserName(username);
        e.setUserPhone(phone);
        e.setCompany(company);
        boolean insert = false;
        try {
             insert = ExpressService.insert(e);
        } catch (DuplicateCodeException duplicateCodeException) {
            duplicateCodeException.printStackTrace();
        }
        Message msg = new Message();

        if(insert){
            msg.setStatus(0);
            msg.setResult("快递添加成功");
        }else{
            msg.setStatus(-1);
            msg.setResult("快递添加失败");
        }
        String s = JSONUtil.toJSON(msg);
        return s;


    }
}
